﻿// MIT License
//
// Copyright (c) 2021-present zuohuaijun, Daming Co.,Ltd and Contributors
//
// 电话/微信：18020030720 QQ群1：87333204 QQ群2：252381476

using Admin.NET.Application.Const;
using Admin.Net.InformationPlatform.Entity;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using Nest;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Admin.Net.InformationPlatform.Service.Product.Dto.Audit;
using Admin.Net.InformationPlatform.Entity.Product;
using Admin.Net.InformationPlatform.Service.Product.Dto;
using Admin.NET.Core;
using MathNet.Numerics.Distributions;
using NPOI.SS.Formula.Functions;
using Admin.Net.InformationPlatform.Service.Product.Dto.T100;

namespace Admin.Net.InformationPlatform.Service.Product;

[ApiDescriptionSettings(groups: "PlaceOrder", Name = "订单审核", Tag = "订单审核操作", Order = 200)]
public class OrderAuditService : IDynamicApiController, ITransient
{
    /// <summary>
    /// 单例数据链接
    /// </summary>
    ISqlSugarClient db;
    /// <summary>
    /// T100数据库
    /// </summary>
    private SqlSugarProvider _T100Db;
    private SqlSugarProvider _SjDb;
    private SqlSugarProvider _plm;
    private SqlSugarProvider _Dilon;
    private SqlSugarProvider _T100TestView;


    /// <summary>
    /// 用户信息
    /// </summary>
    TokenUser _User;
    /// <summary>
    /// 报备客户管理模块
    /// </summary>
    /// <param name="db"></param>
    public OrderAuditService(ISqlSugarClient db)
    {
        this.db = db;
        this._T100Db = this.db.AsTenant().GetConnection(T100Const.ConfigId);
        this._SjDb = this.db.AsTenant().GetConnection(SJDB.ConfigId);
        this._plm = this.db.AsTenant().GetConnection(PLM.ConfigId);
        this._Dilon = this.db.AsTenant().GetConnection(Dilon.ConfigId);
        this._T100TestView = this.db.AsTenant().GetConnection(T100TestView.ConfigId);
        // 获取 `Jwt` 存储的信息 企业编号与据点信息
        _User = Util.SjCommonUtil.GetT100UserTokenInfo(_T100Db, _Dilon);

    }

    /// <summary>
    /// 查询审核订单
    /// </summary>
    [HttpPost("/Order/SelectOrderAuditList")]
    public async Task<SqlSugarPagedList<SelectOrderAuditOutput>> SelectOrderAlreadyAuditList(SelectOrderAuditInput input)
    {

        //验证用户权限

      var orderCustomerList = await _SjDb.Queryable<OrderCustomer>()
      .WhereIF(!string.IsNullOrEmpty(input.OrderId), (l) => (l.ORDERID.Contains(input.OrderId)))//订单编号
      .WhereIF(!string.IsNullOrEmpty(input.UserName), (l) => (l.CUSTOMERNAME.Contains(input.UserName)))//客户简称
      .WhereIF(!string.IsNullOrEmpty(input.CustName), (l) => (l.BUSINESSPERSON.Contains(input.CustName)))//业务员名称
      .WhereIF(input.OrderStartTime != null, b => (SqlFunc.Oracle_ToDate(SqlFunc.Oracle_ToChar(Convert.ToDateTime(b.ORDERDATE), "yyyy-mm-dd"), "yyyy-mm-dd") >= input.OrderStartTime))//下单开始日期
      .WhereIF(input.OrderEndTime != null, b => (SqlFunc.Oracle_ToDate(SqlFunc.Oracle_ToChar(Convert.ToDateTime(b.ORDERDATE), "yyyy-mm-dd"), "yyyy-mm-dd") <= input.OrderEndTime))//下单结束日期
     .OrderBy(l => l.ORDERID, OrderByType.Desc) //订单编号
     .Select(a => new SelectOrderAuditOutput
     {
         OrderId = a.ORDERID,
         UserName = a.CUSTOMERNAME,
         CustNo = a.BUSINESSPERSON,
         CustName = a.CUSTOMERNAME,
         UserNo = a.CUSTOMERID,
         CreateTime = a.ORDERDATE,

     }).ToListAsync();

        int status = 0;
        if (input.OrderStatus)
        {
            status = 1;
        }

        var output = await _SjDb.Queryable<OrderProduct>()
         .WhereIF(!string.IsNullOrEmpty(input.OrderId), (l) => (l.ORDERID == input.OrderId))//订单编号
        //  .WhereIF(!string.IsNullOrEmpty(input.UserName), (l) => (l.CUSTOMERNAME == input.UserName))//客户简称
       // .WhereIF(!string.IsNullOrEmpty(input.SjMid), (l) => (l.SJMID == input.SjMid))//产品料号
        .Where((l) => (l.ORDERSTATUS == status))//产品状态
        .WhereIF(input.OrderStartTime != null, b => (SqlFunc.Oracle_ToDate(SqlFunc.Oracle_ToChar(Convert.ToDateTime(b.ORDERDATE), "yyyy-mm-dd"), "yyyy-mm-dd") >= input.OrderStartTime))//下单开始日期
        .WhereIF(input.OrderEndTime != null, b => (SqlFunc.Oracle_ToDate(SqlFunc.Oracle_ToChar(Convert.ToDateTime(b.ORDERDATE), "yyyy-mm-dd"), "yyyy-mm-dd") <= input.OrderEndTime))//下单结束日期

      .OrderBy(l => l.ORDERID, OrderByType.Desc) //订单编号
      .OrderBy(l => l.ORDERDATE, OrderByType.Desc) //下单日期排序
      .Select(a => new SelectOrderAuditOutput
      {
          OrderId = a.ORDERID,
          UserName = a.CUSTOMERNAME,
          OrderPrice = a.HAVETAXAMOUNT * a.PURCHASEQUANTITY,
          CreateTime = a.ORDERDATE,
          OrderNmber = a.PURCHASEQUANTITY

      }).ToPagedListAsync(input.Page,input.PageSize);

        List<SelectOrderAuditOutput> list1 = (List<SelectOrderAuditOutput>)output.Items;

        List<SelectOrderAuditOutput> list = new List<SelectOrderAuditOutput>();

        if (orderCustomerList.Count != 0 && list1.Count != 0)
        {
            var result = from o in orderCustomerList
                         join c in list1 on o.OrderId equals c.OrderId into OrderId
                         from c in OrderId.DefaultIfEmpty()
                         select new SelectOrderAuditOutput
                         {
                             OrderId = o.OrderId,
                             UserName = o.UserName,
                             CustName = o.CustName,
                             CustNo = o.CustNo,
                             UserNo = o.UserNo,
                             // OrderMessage = //产品信息
                             //  OrderPrice = //订单金额
                             CreateTime = o.CreateTime,
                             //  Number = //订单种数
                           //  OrderNmber = //订单总体数量


                         };

            foreach (var item in output.Items)
            {
                    //订购量
                    int number = _SjDb.Queryable<OrderProduct>()
                           .Where((a) => a.ORDERID == item.OrderId)
                          .Sum(it => it.PURCHASEQUANTITY);

                    //数量
                    int OrderNmber = _SjDb.Queryable<OrderProduct>()
                         .Where((a) => a.ORDERID == item.OrderId)
                        .Count();

                  item.Number = number;
                  item.OrderNmber = OrderNmber;
                  item.OrderMessage = OrderNmber + "种" + number + "件";
            }


        }

      

        return output;
    }

    /// <summary>
    /// 审核订单 调用oa
    /// </summary>
    [HttpPost("/Order/OrderAudit")]
    public async Task<string> AuditOrder() { 
    
    return string.Empty;
    }


    /// <summary>
    /// OA回调接口
    /// </summary>
    [HttpPost("/Order/UpdateOrderStatus")]
    public void UpdateOrderStatus(OrderStatusInput input) {

        if (input!=null && input.OrderStatus!=0) {

            _SjDb.Updateable<OrderProduct>()
            .SetColumns(it => it.ORDERSTATUS == input.OrderStatus)
            .Where(it => it.ORDERID == input.OrderId)
            .ExecuteCommand();
        
        }
    
    
    }
}
